﻿using System;
using System.IO;
using System.Text;

class Program
{
    static string path = @"D:\My\.Net Project\文件操作\FileStream操作\Test.txt";

    static void Main(string[] args)
    {
        /*创建操作*/
        //CreatStream();
        //ReadStream();
        //WriteStream();
        
        Console.ReadKey();
    }
    static void CreatStream()
    {        
        //1.使用构造函数
        FileMode fileMode = FileMode.Create;//文件模式(文件指针放在哪里,文件存在打开后该怎么处理)
        FileAccess fileAccess = FileAccess.Write;//文件权限,想对文件作何操作  
        FileShare share = FileShare.None;//别的程序对此流有哪些权限
        FileStream streamA = new FileStream(path, fileMode, fileAccess);
        //2.直接通过File类获取
        File.OpenRead(path);
        File.Create(path);        
        //... ...
    }
    static void ReadStream(string 不使用using的操作)
    {
        FileStream stream = File.OpenRead(path);
        byte[] arr = new byte[1024];
        int length = 0;//得到每次读取的真实字节数
        
        while (true)
        {
            length = stream.Read(arr, 0, arr.Length);
            if (length == 0) break;//如果读取到0个字节跳出
            //从缓冲区的第0位开始到最后一个length（个数）解码
            string str = Encoding.UTF8.GetString(arr, 0, length);
            //Encoding.GetEncoding("UTF-8").GetString(arr);

            Console.WriteLine(str);
        }
        //关闭流文件
        stream.Close();
    }
    static void ReadStream()
    {
        using (FileStream stream = File.OpenRead(path))
        {//每次读取1字节的数据到缓存区
            byte[] bytes = new byte[1024];
            int length = 0;//当前这次读取到了多长的数据(字节数)

            while (true)
            {
                length = stream.Read(bytes, 0, bytes.Length);
                if (length == 0) break;
                string text = Encoding.GetEncoding("UTF-8")
                    .GetString(bytes, 0, bytes.Length);
                Console.WriteLine(text);
            }
        }
    }
    static void WriteStream()
    {//注意如果这里面传递的是FileStream那么写入的数据是中文，不然就是16进制的数。或者是使用path,bool,encoding来转码
        using (FileStream stream = File.Create(@"D:\test.txt"))
        {
            while (true)
            {
                string input = Console.ReadLine();
                if (input == "Exit()") break;
                byte[] bytes = Encoding.UTF8.GetBytes(input);
                stream.Write(bytes, 0, bytes.Length); //先写入底层缓冲区(到一定量之后才会写入硬盘)
            }
            stream.Flush();//把流运送过去,因为每次写文件不是计时的如果用using可以不加
        }
    }
}